package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.common.exception.CustException;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.constants.AdminConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description:
 * @Version: V1.0
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {


    /**
     * 用户登录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(AdUserDto dto) {

        //1 参数校验
//        if (dto == null || StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword())) {
//            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
//        }

        //2 根据用户名查询用户信息，获取盐
       AdUser adUser =  getOne(Wrappers.<AdUser>lambdaQuery()
                .eq(AdUser::getName, dto.getName())
                .eq(AdUser::getStatus, AdminConstants.ADUSER_NORMAL_STATUS)
                 );
        if (adUser == null) {
            CustException.cust(AppHttpCodeEnum.ADMIN_ADUSER_ISNTOEXIT_ERROR );
        }
        // 盐
        String salt = adUser.getSalt();
        String dbpassword = adUser.getPassword();  // 加密后的密码

        //3 按照相同的加密方式加密，比对密码
        // MD5（"123456"+salt）
        String npwd = DigestUtils.md5DigestAsHex((dto.getPassword() + salt).getBytes());
        if (!dbpassword.equals(npwd)) {
            CustException.cust(AppHttpCodeEnum.ADMIN_ADUSER_NAMEORPWD_ERROR );
        }

        //4 更新登录时间
        adUser.setLoginTime(new Date());
        updateById(adUser);


        //5 生成token和用户信息返回给前端  JWT令牌
        String token = AppJwtUtil.getToken(adUser.getId().longValue());

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("token", token);

        adUser.setPassword(null);
        adUser.setSalt(null);
        resultMap.put("user", adUser);

        return ResponseResult.okResult(resultMap);
    }




}
